package framework.runtime;

import framework.utils.CharsetUtil;
import framework.utils.JsonUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.View;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

/**
 * JSON视图模板
 */
@Slf4j
public class JsonDataView implements View {

    @Setter
    @Getter
    private Object data;

    public JsonDataView() {

    }

    public JsonDataView(Object data) {
        this.data = data;
    }

    @Override
    public String getContentType() {
        return MediaType.APPLICATION_JSON_VALUE;
    }

    @Override
    public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String json = this.buildJson(this.data);
        response.setContentType(this.getContentType());
        response.setCharacterEncoding(CharsetUtil.getSystemCharset());
        try (PrintWriter writer = response.getWriter()) {
            writer.write(json);
            writer.flush();
        }
    }

    protected String buildJson(Object data) {
        if (data == null) return "{}";
        String json = JsonUtil.toJsonString(data);
        return json;
    }
}
